<template>
    <div class="p-2">
        <searchrevealing>
            <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="98px">
                <el-form-item label="供应商名称" prop="supplierName">
                    <el-input style="width: 220px" v-model="queryParams.supplierName" placeholder="请输入供应商名称"
                        maxlength="20" @keyup.enter="handleQuery"></el-input>
                </el-form-item>
                <el-form-item label="是否已签合同" prop="sellStatus">
                    <el-select style="width: 220px" v-model="queryParams.sellStatus" placeholder="请选择" filterable
                        clearable>
                        <el-option v-for="dict in contractStatusList" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="供应商类型" prop="supplierType">
                    <el-select style="width: 220px" v-model="queryParams.supplierType" placeholder="请选择" filterable
                        clearable>
                        <el-option v-for="dict in hm_supplier_type" :key="dict.dictValue" :label="dict.dictLabel"
                            :value="dict.dictValue" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                    <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
                </el-form-item>
            </el-form>
        </searchrevealing>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button v-hasPermi="['hm:supplier:add']" type="primary"
                            @click="handleDetails('add')">新增供应商</el-button>
                    </el-col>
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'招商供应商管理'"
                        @updateColumn="getColmun"></right-toolbar>
                </el-row>
            </template>
            <el-table v-loading="loading" :data="contractList" border @header-dragend="dragEnd">
                <el-table-column v-for="(item, index) in supplierColumns" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <span v-if="item.prop == 'recruiterDepts'">
                            {{ handleExtraData(scope.row.extraData, 'recruiterDeptName') }}
                        </span>
                        <span v-if="item.prop == 'recruiters'">
                            {{ handleExtraData(scope.row.extraData, 'recruiterName') }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150"
                    fixed="right">
                    <template #default="scope">
                        <div class="operation">
                            <el-button v-hasPermi="['supplier:details:look']" link type="primary"
                                @click="handleDetails('look', scope.row)">
                                详情</el-button>
                            <el-button link type="primary" @click="handleDetails('edit', scope.row)">
                                编辑</el-button>
                            <el-dropdown v-hasPermi="['supplier:contract:add']">
                                <span class="el-dropdown-link" style="display: flex;">
                                    上传合同
                                    <el-icon class="el-icon--right">
                                        <arrow-down />
                                    </el-icon>
                                </span>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item
                                            @click="uploadContractFile(scope.row, '供销合同')">供销合同</el-dropdown-item>
                                        <el-dropdown-item
                                            @click="uploadContractFile(scope.row, '破价合同')">破价合同</el-dropdown-item>
                                        <el-dropdown-item
                                            @click="uploadContractFile(scope.row, '保证金协议')">保证金协议</el-dropdown-item>
                                        <el-dropdown-item
                                            @click="uploadContractFile(scope.row, '补充协议')">补充协议</el-dropdown-item>
                                        <el-dropdown-item
                                            @click="uploadContractFile(scope.row, '包销合同')">包销合同</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>

                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" />

        </el-card>
        <!-- 上传合同 -->
        <contractFile @doClose="contractFileClose" :contractFileData="contractFileData"
            :contractFileVisible="contractFileVisible"></contractFile>
        <contractDetails @doClose="contractDetailsClose" :contractDetailsData="contractDetailsData"
            :contractDetailsVisible="contractDetailsVisible"></contractDetails>
    </div>
</template>

<script setup name="Contract" lang="ts">
import { ContractQueryParams, ContractTable } from '@/api/group/contract/types'
import { getDeptList, getUserById } from '@/api/group/qualityControl'
import { listHmContract, getHmContract } from '@/api/system/hmContract';
import { getDicts } from '@/api/system/dict/data/index'
import contractFile from './compoments/contractFile.vue';
import contractDetails from './compoments/contractDetails.vue';
import { listColumn } from '@/api/system/column';
const { proxy } = getCurrentInstance() as any;
const supplierColumns = ref()
const columnData = ref()

const queryFormRef = ref<ElFormInstance>();
const showSearch = ref(true);
const activeTab = ref('contract');
const loading = ref(true);
const total = ref(0);
const contractList = ref<ContractTable[]>([]);
const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])
const contractFileVisible = ref(false)
const contractFileData = ref<ContractTable>()
const contractDetailsVisible = ref(false)
const contractDetailsData = ref<any>()
const hm_supplier_type = ref()
const queryLoading = ref(false)
const contractStatusList = ref([
    { label: '是', value: '1' },
    { label: '否', value: '0' },
])
const router = useRouter();

const queryParams = reactive<ContractQueryParams>({
    pageNum: 1,
    pageSize: 10,
    supplierName: undefined,
    recruiterDept: undefined,
    recruiter: undefined,
    sellStatus: undefined,
    supplierType: undefined,
})

/** 根据合同类型获取合同名称 */
const contractNameByType = async (type: string, row: any) => {
    if (row) {
        const rows = row.filter((item: any) =>
            item.contractType == type
        )
        if (rows.length > 0) {
            return rows[0].fileName
        } else {
            return ''
        }
    } else {
        return ''
    }
}

/**
 * 获取招商部门信息
 */
const getDeptLists = async () => {
    const res = await getDeptList({ parentId: '1782395704411734018' })
    deptList.value = res.data
}
/** 获取供应商类型字典 */
const getDictsList = async () => {
    const res = await getDicts('hm_supplier_type')
    hm_supplier_type.value = res.data
}

/** 搜索按钮操作 */
const handleQuery = () => {
    queryLoading.value = true
    queryParams.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};
/** 我的意向关闭 */
const contractFileClose = () => {
    contractFileVisible.value = false;
    getList();
};
/** 查看详情关闭 */
const contractDetailsClose = () => {
    contractDetailsVisible.value = false;
    getList();
}
/** 招商部招商员多个回显 */
const handleExtraData = (data: any, recruiterDeptName: string) => {
    if (data) {
        const list: any[] = [];
        data.forEach((element: any) => {
            list.push(element[recruiterDeptName]);
        });
        return list.join(",");
    }
};
/** 上传合同 */
const uploadContractFile = async (row: ContractTable, type: string) => {
    const rows = row.contractList.filter((item: any) => {
        return item.contractType == type
    })
    if (rows.length > 0) {
        const res = await getHmContract(rows[0].id);
        contractFileVisible.value = true;
        contractFileData.value = res.data;
    } else {
        contractFileVisible.value = true;
        (contractFileData.value as any) = {
            contractType: type,
            supplierId: row.id
        };
    }
};

/** 新增，修改，查看供应商 */
const handleDetails = async (type: string, row?: ContractTable) => {
    router.push({
        path: '/suppliers/contractDetail',
        query: {
            supplierId: row ? row.id : '',
            routerType: type
        }
    })
}

/** 合同列表 */
const getList = async () => {
    try {
        loading.value = true;
        const res = await listHmContract(queryParams);
        const updatedRows = await Promise.all(res.rows.map(async (row: ContractTable) => {
            // 为每个合同类型调用contractNameByType并获取合同名称  
            const contractSellName = await contractNameByType('供销合同', row.contractList);
            const contractDiscountName = await contractNameByType('破价合同', row.contractList);
            const marginName = await contractNameByType('保证金协议', row.contractList);
            const supplementary = await contractNameByType('补充协议', row.contractList);
            const packageStatus = await contractNameByType('包销合同', row.contractList);
            row.contractSellName = contractSellName;
            row.contractDiscountName = contractDiscountName;
            row.marginName = marginName;
            row.supplementary = supplementary;
            row.packageStatus = packageStatus;
            return row;
        }));
        contractList.value = updatedRows;

        // contractList.value = res.rows;
        total.value = res.total;
        loading.value = false;
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
};
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.pageSize)
    getColmun()
}
/** 获取colmun */
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('招商供应商管理')
    supplierColumns.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.pageSize)
}
onMounted(async () => {
    queryParams.pageNum = 1;
    await getColmun();
    await getList();
    getDictsList();
    getDeptLists();
});
</script>
<style lang="scss" scoped>
.operation {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: center;
}

.el-dropdown {
    font-size: 14px !important;
}
</style>